package com.zy.explore.license.application.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.explore.license.domain.mybatis.dao.SysEventLogDao;
import com.zy.explore.license.domain.mybatis.dao.SysMenuDao;
import com.zy.explore.license.domain.mybatis.dao.SysRoleDao;
import com.zy.explore.license.domain.mybatis.dao.SysUserDao;
import com.zy.explore.license.domain.mybatis.dao.UserRoleDao;
import com.zy.explore.license.domain.mybatis.entity.SysMenu;
import com.zy.explore.license.domain.mybatis.entity.SysRole;
import com.zy.explore.license.domain.mybatis.entity.SysUser;
import com.zy.explore.license.domain.mybatis.entity.UserRole;
import com.zy.explore.license.infrastructure.util.JwtUtil;
import com.zy.explore.license.interfaces.frm.CheckPwdFrm;
import com.zy.explore.license.interfaces.frm.ModifyPwdFrm;
import com.zy.explore.license.interfaces.vo.LastLoginInfoVO;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 系统用户表(表sys_user)服务接口实现类
 *
 * @author ChinaYin  主页:https://gitee.com/zy-explorej2ee 邮箱:zyexplorej2ee@sina.com
 * @date 2021年06月13日 13:33:16
 */
@Service
public class SysUserService extends ServiceImpl<SysUserDao, SysUser> {

    @Resource
    private SysRoleDao sysRoleDao;

    @Resource
    private SysMenuDao sysMenuDao;

    @Resource
    private UserRoleDao userRoleDao;

    @Resource
    private SysEventLogDao sysEventLogDao;

    /**
     * 通过用户名查询用户对象
     *
     * @param username 用户名
     * @return 返回用户对象
     */
    public SysUser getUserByUsername(String username) {
        return baseMapper.getUserByUsername(username);
    }

    /**
     * 查询用户的角色集合
     *
     * @param userId 用户ID
     * @return 返回用户的角色集合
     */
    public List<SysRole> getUserRoleList(Integer userId) {
        List<SysRole> roles = sysRoleDao.getUserRoleList(userId);
        if (CollectionUtils.isEmpty(roles)) {
            return new ArrayList<>();
        }
        return roles;
    }

    /**
     * 查询用户的菜单集合
     *
     * @param userId 用户ID
     * @return 返回用户的菜单集合
     */
    public List<SysMenu> getUserMenuList(Integer userId) {
        List<SysMenu> menuList = sysMenuDao.getMenuList(userId);
        if (CollectionUtils.isEmpty(menuList)) {
            return new ArrayList<>();
        }
        return menuList;
    }

    /**
     * 校验用户密码是否正确
     *
     * @param frm 检验参数
     * @return 返回1:正确 0:不正确
     */
    public Integer checkPwd(CheckPwdFrm frm) {
        String pwd = frm.getPwd();
        Integer userId = JwtUtil.getCurrentUserId();
        SysUser sysUser = super.getById(userId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(sysUser != null && encoder.matches(pwd, sysUser.getPassword())) {
            return 1;
        }
        return 0;
    }

    /**
     * 修改密码
     *
     * @param frm 修改密码参数
     * @return 返回1:成功 0:失败
     */
    public Integer modifyPwd(ModifyPwdFrm frm) {
        Integer currentUserId = JwtUtil.getCurrentUserId();
        String oldPwd = frm.getOldPwd();
        String newPwd = frm.getNewPwd();
        if (Objects.equals(oldPwd, newPwd)) {
            return 1;
        }
        SysUser sysUser = super.getById(currentUserId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (sysUser != null && encoder.matches(oldPwd, sysUser.getPassword())) {
            sysUser.setPassword(encoder.encode(newPwd));
            super.updateById(sysUser);
            return 1;
        }
        return 0;
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String guest = encoder.encode("guest");
        System.out.println(guest);
        System.out.println(encoder.matches("guest", "$2a$10$k97j7MJolSO4lSOzI3mUjeKTVpnPi8Qe1r0roTguv2uN9.3IAg/ma"));
    }

    /**
     * 查询用户上次登录信息
     *
     * @param userId 用户ID
     * @return 返回上次登录信息
     */
    public LastLoginInfoVO getLastLoginInfo(Integer userId) {
        LastLoginInfoVO info = sysEventLogDao.getLastLoginInfo(userId);
        if (info == null) {
            return LastLoginInfoVO.builder().lastLoginIp("无").lastLoginTime("无").build();
        }
        return info;
    }

    /**
     * 添加角色
     *
     * @param userIdList 用户id列表
     * @param roleIdList 角色id列表
     */
    public void addRole(List<Integer> userIdList, List<Integer> roleIdList) {
        if (CollectionUtils.isEmpty(userIdList) || CollectionUtils.isEmpty(roleIdList)) {
            return;
        }
        userIdList.forEach(userId -> roleIdList.forEach(roleId -> userRoleDao.insert(UserRole.builder().userId(userId).roleId(roleId).build())));
    }
}